/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-11-30 11:27:09
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-04-17 17:13:51
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
    addCorp,
    removeCorp,
    updateCorp,
} from '@/api/system/corp';
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { CorpDomain } from '@/type.d/system';
import { Space, Button, Modal, Form, Input, Radio, Row, Col } from 'antd';
import React, { Ref, forwardRef, useEffect, useState } from 'react'
import './index.less';

interface CorpCardProp {
    statusOptions: any[];
    /**
     * 卡片数据 受控
     */
    cardData: CorpDomain;
    /**
     * 卡片新增时的默认数据
     */
    newdata?: CorpDomain;
    /**
     * 列表数据
     */
    tableListDataSource: CorpDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: CorpDomain[]) => void;

    setIsedit?: (isedit: boolean) => void;

    isedit?: boolean;
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
export type CorpCardInstance = {
    setIsedit: (isedit: boolean) => void
}
type CorpCardRef = React.MutableRefObject<CorpCardInstance | undefined> | React.RefObject<CorpCardInstance | undefined>

const CorpCard = forwardRef((props: CorpCardProp,ref: Ref<any>) => {
    const { statusOptions, cardData, newdata = {}, tableListDataSource, setTableListDataSource, setIsedit, isedit = false, onBack } = props;
    const { layoutStore, userStore } = useStore();
    const [selectdata, setSelectdata] = useState<CorpDomain>(cardData);
    const [oldSelectdata, setOldSelectdata] = useState<CorpDomain>({});//编辑状态临时保存选中的菜单树数据
    const [formRef] = Form.useForm<CorpDomain>();

    const intCardData = (_cardData: CorpDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata(_cardData)
    }



    const addCardData = (_cardData: CorpDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
    }

    const onDelete = (dedata: CorpDomain) => {
        if (dedata.pkCorp) {
            layoutStore.OpenSpanning()
            removeCorp(dedata.pkCorp).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.pkCorp !== dedata.pkCorp
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }
    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [])


    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef?.setFieldsValue({ ...selectdata });
        } else {
            formRef?.setFieldsValue({});
        }
    }, [selectdata])

    /**
    * 表单字段配置
    */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6}>
                <Form.Item name="pkFathercorp" label="上级公司">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="corpName" label="公司名称" rules={[{required: true,message: "公司名称不能为空"}]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="corpCode" label="公司编码" rules={[{required: true,message: "公司编码不能为空"}]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="taxpayerid" label="企业信用代码">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="leader" label="负责人">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="phone" label="联系电话">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="address" label="联系地址">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="enablestate" label="启用状态">
                    <Radio.Group options={statusOptions} disabled />
                </Form.Item>
            </Col>
            <Col md={24} xl={24}>
                <Form.Item name="remark" label="备注">
                    <Input.TextArea />
                </Form.Item>
            </Col>
        </Row >;

    const cardbuttons = (
        <Space>
            <Button
                hidden={!userStore.hasPerms('system:corp:add')}
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata, pkFathercorp: selectdata.pkCorp })
                }}
            >
                新增
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:corp:edit')}
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.pkCorp ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:corp:delete')}
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.pkCorp ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>
    )

    const onSave = () => {

        formRef.validateFields().then((validInfo) => {
            const data: CorpDomain = formRef?.getFieldsValue() || {};
            if (!selectdata.pkCorp) {//新增
                layoutStore.OpenSpanning()
                addCorp({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据

                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])//更新列表数据

                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updateCorp({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    //更新列表数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.pkCorp === res.data.pkCorp) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })


    }

    const editbuttions = (<Space>
        <Button
            size='small'
            key="save"
            type="primary"
            onClick={() => {
                onSave()
            }}
        >
            保存
        </Button>
        <Button
            size='small'
            key="cancel"
            type="primary"
            onClick={() => {
                resetCardData()
                setIsedit?.(false)
            }}
        >
            取消
        </Button>
    </Space>)

    return (
        <BillCard
            formid='pkCorp'
            key={'corpCard'}
            formRef={formRef}
            isedit={isedit}
            extraButton={isedit ? editbuttions : cardbuttons}
            onBack={onBack}
            title={'公司管理'}
            cardItem={cardItems}
        />

    )
})
export default CorpCard;